package com.carzone.placeholder.util;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import com.carzone.placeholder.template.AbstractPropertiesTemplate;
import com.google.common.collect.Maps;

public class PlaceholderUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(PlaceholderUtil.class);

	private static final String PLACEHOLDER = "placeholder.properties";

	public static Map<String, AbstractPropertiesTemplate> readProperties() {
		Map<String, AbstractPropertiesTemplate> map = Maps.newHashMap();
		try {
			Properties properties = PropertiesLoaderUtils.loadProperties(new ClassPathResource(PLACEHOLDER));
			Set<Entry<Object, Object>> set = properties.entrySet();

			for (Iterator<Entry<Object, Object>> iterator = set.iterator(); iterator.hasNext();) {
				Entry<Object, Object> entry = iterator.next();
				String key = (String) entry.getKey();
				Object value = entry.getValue();
				Class<?> clazz = Class.forName((String) value);
				if (AbstractPropertiesTemplate.class.isAssignableFrom(clazz)) {
					if (!map.containsKey(key)) {
						AbstractPropertiesTemplate abstractPropertiesTemplate = (AbstractPropertiesTemplate) clazz
								.newInstance();
						map.put(key, abstractPropertiesTemplate);
					} else {
						LOGGER.error("{}名称已存在", key);
						throw new RuntimeException(key + "名称已存在");
					}
				} else {
					LOGGER.error(PLACEHOLDER + "里面的类必须是AbstractPropertiesTemplate的子类");
					throw new RuntimeException("里面的类必须是AbstractPropertiesTemplate的子类");
				}
			}
			LOGGER.info("读取{}内容：{}", PLACEHOLDER, map);
		} catch (IOException e) {
			e.printStackTrace();
			LOGGER.error("读取{}文件异常", PLACEHOLDER, e);
		} catch (InstantiationException e) {
			e.printStackTrace();
			LOGGER.error("读取{}文件异常,实例化异常", PLACEHOLDER, e);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			LOGGER.error("读取{}文件异常,实例化异常", PLACEHOLDER, e);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			LOGGER.error("读取{}文件异常,类型转换异常", PLACEHOLDER, e);
		}
		return map;
	}
}
